package com.kaiwukj.android.ufamily.mvp.http.interceptor;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.LogUtils;
import com.kaiwukj.android.ufamily.app.constant.Constant;
import com.kaiwukj.android.ufamily.mvp.http.api.Api;

import java.io.IOException;
import java.util.List;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class HostInterceptor implements Interceptor {
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {

//        LogUtils.d("------------intercept--------------");

        Request request = chain.request();
        HttpUrl oldHttpUrl = request.url();

        Request.Builder builder = request.newBuilder();

        List<String> headerValues = request.headers("url_name");
        if (headerValues != null && headerValues.size() > 0) {
            builder.removeHeader("url_name");
            String headerValue = headerValues.get(0);
            HttpUrl newBaseUrl;
            if ("shop".equals(headerValue)) {
                newBaseUrl = HttpUrl.parse(Constant.getShopHost());
            } else {
                newBaseUrl = oldHttpUrl;
            }

            HttpUrl newFullUrl = oldHttpUrl.newBuilder()
                    .host(newBaseUrl.host())
                    .port(newBaseUrl.port())
                    //.removePathSegment(0)
                    .build();

            LogUtils.d("url------------------>" + newFullUrl.toString());

            return chain.proceed(builder.url(newFullUrl).build());
        }
        return chain.proceed(request);
    }
}
